package tn.orange.canreminder.helper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import tn.orange.canreminder.model.Competition;
import tn.orange.canreminder.model.Country;
import tn.orange.canreminder.singleton.CompetitionSingleton;
import tn.orange.canreminder.singleton.CountrySingleton;
import tn.orange.canreminder.utils.DateUtils;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;

public class CalendrierHelper {

	public static void saveIntoCalenndar(String equipe, Context context, int min)
			throws Exception {

		List<Competition> competitions = CompetitionSingleton.getInstance();
		List<String> values = new ArrayList<String>();
		values.add(equipe);
		List<Competition> newCompetitions = CompetitionHelper
				.getCompetitionbyEquipe(values, competitions);
		for (Competition competition : newCompetitions) {
			InsertOrUpdateEvent(context, competition, min, equipe);
		}

	}

	public static void InsertOrUpdateEvent(Context context,
			Competition competition, int min, String equipe) {

		List<Country> countries = CountrySingleton.getInstance();

		Country country1 = countries.get(getCountryPosition(
				competition.getCountryone_id(), countries));
		Country country2 = countries.get(getCountryPosition(
				competition.getCountrytwo_id(), countries));

		Date date = DateUtils.stringToDate(competition.getCompetitiondate());

		String id = getCalendarId(date, context);

		ContentValues l_event = new ContentValues();

		l_event.put("calendar_id", "1");
		l_event.put("title", " Match : " + country1.getName() + " VS "
				+ country2.getName());
		l_event.put("eventLocation", "Gabon | Guinée ");
		l_event.put("dtstart", date.getTime());
		l_event.put("dtend", date.getTime() + 7200 * 1000);
		l_event.put("allDay", 0);
		// status: 0~ tentative; 1~ confirmed; 2~ canceled
		l_event.put("eventStatus", 1);
		// 0~ default; 1~ confidential; 2~ private; 3~ public
		l_event.put("visibility", 0);
		// 0~ opaque, no timing conflict is allowed; 1~ transparency, allow
		// overlap of scheduling
		l_event.put("transparency", 1);
		// 0~ false; 1~ true

		if (min == -1)
			l_event.put("hasAlarm", 0);
		else
			l_event.put("hasAlarm", 1);

		Uri l_eventUri;
		if (Build.VERSION.SDK_INT >= 8) {
			l_eventUri = Uri.parse("content://com.android.calendar/events");

		} else {
			l_eventUri = Uri.parse("content://calendar/events");
		}
		Uri l_uri;
		if (id == "-1") {
			l_uri = context.getContentResolver().insert(l_eventUri, l_event);
			id = l_uri.getLastPathSegment();

		} else {
			int id_event = Integer.parseInt(id);

			Uri updateEventUri = ContentUris.withAppendedId(l_eventUri,
					id_event);
			context.getContentResolver().update(updateEventUri, l_event, null,
					null);

		}
		if (min != -1) {

			ContentValues values = new ContentValues();
			values.put("event_id", id);
			values.put("method", 1);
			values.put("minutes", min);
			Uri eventsURI = Uri
					.parse("content://com.android.calendar/reminders");
			context.getContentResolver().delete(eventsURI, "event_id==" + id,
					null);
			context.getContentResolver().insert(eventsURI, values);
		}
	}

	private static int getCountryPosition(int id, List<Country> countries) {
		int i = 0;
		for (Country country : countries) {

			if (country.getId() == id)
				return i;
			i++;
		}
		return -1;
	}

	public static int convertTominutes(String selectedItem) {

		int minutes = 0;

		if (selectedItem.equals("A l'heure"))
			minutes = 0;
		if (selectedItem.equals("5 minutes avant"))
			minutes = 5;
		if (selectedItem.equals("15 minutes avant"))
			minutes = 15;
		if (selectedItem.equals("1 heure avant"))
			minutes = 60;
		if (selectedItem.equals("1 jour avant"))
			minutes = 1440;

		return minutes;

	}

	public static String getCalendarId(Date date, Context context) {

		String[] projection = new String[] { "_id" };
		Uri calendars;
		if (Build.VERSION.SDK_INT >= 8) {
			calendars = Uri.parse("content://com.android.calendar/events");
		} else {
			calendars = Uri.parse("content://calendar/events");
		}

		String where = "dtstart==" + date.getTime();

		Cursor managedCursor = context.getContentResolver().query(calendars,
				projection, where, null, null);
		String calId = "-1";

		if (managedCursor == null)
			return calId;
		if (managedCursor.moveToFirst()) {

			int idColumn = managedCursor.getColumnIndex("_id");
			do {
				calId = managedCursor.getString(idColumn);
				break;
			} while (managedCursor.moveToNext());
		}
		return calId;

	}

	public static int getPositionOfTime(String selectedItem) {

		if (selectedItem.equals("0"))
			return 0;
		if (selectedItem.equals("5"))
			return 1;
		if (selectedItem.equals("15"))
			return 2;
		if (selectedItem.equals("60"))
			return 3;
		if (selectedItem.equals("1440"))
			return 4;

		return -1;

	}

	public static String getSelectedTime(String selectedItem) {

		if (selectedItem == null)
			return "désactivé";

		if (selectedItem.equals("0"))
			return "à l'heure";
		if (selectedItem.equals("5"))
			return "5 minutes avant";
		if (selectedItem.equals("15"))
			return "15 minutes avant";
		if (selectedItem.equals("60"))
			return "1 heure avant";
		if (selectedItem.equals("1440"))
			return "1 jour avant";

		return "désactivé";

	}

	public static void saveMatchIntoCalenndar(Competition competition,
			Context applicationContext, int min) {

		InsertOrUpdateEvent(applicationContext, competition, min, " ");
		// TODO Auto-generated method stub

	}
}
